/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2009, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: MSG_to_IMAGE.cpp 33238 2010-03-11 00:46:58Z rusu $
 *
 */

// ROS core
#include <ros/ros.h>
#include <cmath> 
#include <math.h>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <iostream>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>

// STL
#include <string>

/**
\author Radu Bogdan Rusu
@b MSG_to_IMAGE is a simple node that retrieves a ROS point image_msg message and saves it to disk into a IMAGE (Point
image_msg Data) file format.
**/
class MSGToIMAGE
{
protected:
  ros::NodeHandle nh_;

private:
  std::string prefix_;
  std::string postfix_;
  int64_t last_save_time_=0;
  cv::Mat image_;
    std::vector<int> compression_params_;

public:
  std::string image_topic_;
  std::string save_dir_;

  ros::Subscriber sub_;

  ////////////////////////////////////////////////////////////////////////////////
  // Callback
  void
  image_cb(const sensor_msgs::ImageConstPtr& image_msg)
  {
    
    image_ = cv_bridge::toCvShare(image_msg, "bgr8")->image;

    std::stringstream ss;
    int64_t second_fraction = int64_t(image_msg->header.stamp.nsec/1000);
    int64_t timestamp_floor = int64_t(image_msg->header.stamp.sec)*1000000;
    int64_t timestamp = timestamp_floor + second_fraction;
    // std::cout<<"timestamp "<<timestamp<<std::endl;
    
    int64_t save_name;
    if (second_fraction>=0 && second_fraction < 500000)
    {
      save_name = timestamp_floor + 250000;
    } else
    {
      save_name = timestamp_floor+750000;
    }

    ss << prefix_ << std::to_string(save_name)<<"_"<<postfix_<< ".jpg";

    int64_t time_diff = abs(timestamp - save_name);
    // std::cout<<"save name "<<save_name<<std::endl;
    // std::cout<<"time diff "<<time_diff<<std::endl;
    // std::cout<<"last time diff "<<abs(save_name - last_save_time_)<<std::endl;
    if (time_diff > abs(save_name - last_save_time_) || time_diff > 65000)
    {
      return;
    }

    last_save_time_ = timestamp;

    // ROS_INFO("Data saved to %s", ss.str().c_str());
    cv::imwrite(ss.str().c_str(), image_, compression_params_);
  }

  ////////////////////////////////////////////////////////////////////////////////
  MSGToIMAGE()
  {
    // Check if a prefix parameter is defined for output file names.
    ros::NodeHandle priv_nh("~");
    if (priv_nh.getParam("prefix", prefix_)) {
      ROS_INFO_STREAM("IMAGE file prefix is: " << prefix_);
    } else if (nh_.getParam("prefix", prefix_)) {
      ROS_WARN_STREAM(
        "Non-private IMAGE prefix parameter is DEPRECATED: " <<
          prefix_);
    }
    if (priv_nh.getParam("postfix", postfix_)) {
      ROS_INFO_STREAM("IMAGE file postfix is: " << postfix_);
    } else if (nh_.getParam("postfix", postfix_)) {
      ROS_WARN_STREAM(
        "Non-private IMAGE postfix parameter is DEPRECATED: " <<
          postfix_);
    }

    image_topic_ = "imageinput";

    sub_ = nh_.subscribe(image_topic_, 50, &MSGToIMAGE::image_cb, this);
    ROS_INFO(
      "Listening for incoming data on topic %s",
      nh_.resolveName(image_topic_).c_str());
    
    compression_params_.push_back(cv::IMWRITE_JPEG_QUALITY);
    compression_params_.push_back(80);
  }
};

/* ---[ */
int
main(int argc, char ** argv)
{
  ros::init(argc, argv, "save_image", ros::init_options::AnonymousName);

  MSGToIMAGE b;
  ros::spin();

  return 0;
}
/* ]--- */
